import asyncio
import logging
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import AsyncSessionLocal
from app.services.contract_service import ContractService
from app.services.price_service import price_service

logger = logging.getLogger(__name__)


class SchedulerService:
    def __init__(self):
        self.scheduler = AsyncIOScheduler()
        self.running = False
    
    async def start(self):
        """Start the scheduler"""
        if self.running:
            return
        
        self.running = True
        
        # Add jobs
        self.scheduler.add_job(
            self._settle_expired_contracts,
            IntervalTrigger(seconds=10),  # Check every 10 seconds
            id="settle_contracts",
            name="Settle expired contracts"
        )
        
        self.scheduler.add_job(
            self._save_price_data,
            IntervalTrigger(seconds=5),  # Save prices every 5 seconds
            id="save_prices",
            name="Save price data"
        )
        
        self.scheduler.start()
        logger.info("Scheduler started")
    
    async def stop(self):
        """Stop the scheduler"""
        if not self.running:
            return
        
        self.running = False
        self.scheduler.shutdown()
        logger.info("Scheduler stopped")
    
    async def _settle_expired_contracts(self):
        """Settle expired contracts"""
        try:
            async with AsyncSessionLocal() as db:
                current_timestamp = int(datetime.now().timestamp() * 1000)
                expired_contracts = await ContractService.get_expired_contracts(db, current_timestamp)
                
                if expired_contracts:
                    logger.info(f"Found {len(expired_contracts)} expired contracts to settle")
                    
                    for contract in expired_contracts:
                        try:
                            await ContractService.settle_contract(db, contract)
                            logger.info(f"Settled contract {contract.id}")
                        except Exception as e:
                            logger.error(f"Error settling contract {contract.id}: {e}")
                
        except Exception as e:
            logger.error(f"Error in settle_expired_contracts: {e}")
    
    async def _save_price_data(self):
        """Save current price data to database"""
        try:
            async with AsyncSessionLocal() as db:
                latest_prices = price_service.get_all_latest_prices()
                
                for symbol, price_data in latest_prices.items():
                    try:
                        await ContractService.save_price_data(db, price_data)
                    except Exception as e:
                        logger.error(f"Error saving price data for {symbol}: {e}")
                        
        except Exception as e:
            logger.error(f"Error in save_price_data: {e}")


# Global scheduler service instance
scheduler_service = SchedulerService()
